Table of Content¶

  • 1. Introduction to D3
  • 2. Selection and Manipulation
  • 3. Data Loading and binding
  • 5. Creates a simple bar chart
  • 6. Create labels
  • 7. Scales
  • 8. Axes
  • 9. Create SVG Elements
  • 10. Create a pie chart
  • 11. Create a line chart
  • Credits & References

1. Introduction to D3¶

  • Open source JS library
  • Create visual representation of data
  • Create DOM element using data

2. Selection and Manipulation¶

  • To use D3, we need to import it. We can import it using HTML script tag.

<script src="https://d3js.org/d3.v4.min.js"></script>

  • We can select existing DOM elements using D3 using d3.select() and d3.selectAll() for selecting single and multiple elements respectively.

Example: selection and manipulating DOM element using D3

image.png

3. Data Loading and binding¶

  • We can map data into DOM element using D3 (can manipulate DOM element using our dataset) using .data().enter() method.
    • .data() assign the dataset we want to use
    • .enter() take data items one by one and perform further operations on them. Whatever operations below .enter() is perform on each of the data items individually.

Example 2: How to assign data item to DOM element

image.png

5. Creates a simple bar chart¶

Example of a simple barchart

  • Each of the bar inside the barchart is actually is a html <rect> element

image.png

6. Create labels¶

Example of creating text annotation to each of bar element in the barchart

image.png

7. Scales¶

  • Functions that can transform our data for better visualization.
  • This is useful when we have too small or too high values in our dataset.

Example of scaled dataset

image.png

8. Axes¶

  • To create axes for our chart in d3, we can use d3.axisTop(), d3.axisRight(), d3.axisBottom(), d3.axisLeft().

9. Create SVG Elements¶

Example of SVG Elements

  • List of SVG Element reference in MDN Docs: https://developer.mozilla.org/en-US/docs/Web/SVG/Element

image.png

10. Create a pie chart¶

Example of creating a pie chart

  • Each pie slice is a group element

image.png

11. Create a line chart¶

Example of creating a line chart

  • await lets us wait until async function is done before proceed with the rest of the code. This lets us to run the code top to bottom as we'd expect. If not, then it will not wait for the function to finish and continue running the rest of the code.

image.png

Credits & References¶

  • The course: https://v1.scrimba.com/learn/d3js
  • D3 gallery: https://observablehq.com/@d3/gallery